﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommonRemoting;
using System.Collections;
using System.Configuration;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;
using ProtocoloCarSharing;


namespace ServidorCommunications
{

    public class Remoting : MarshalByRefObject
    {
        private static Remoting Instancia = null;

        public static Remoting GetInstancia()
        {
            if (Instancia == null)
            {
                Instancia = new Remoting();
            }

            return Instancia;
        }

        private Remoting()
        {

        }

        public MensajeProtocolo EnviarMensajeAServCobro(MensajeProtocolo msj) 
        {
            try
            {
                string dir = (ConfigurationManager.AppSettings["dirServCobroRemoting"]);

                if (RemotingConfiguration.IsRemotelyActivatedClientType(typeof(IServCobro)) == null)
                {
                    //TcpChannel chan = new TcpChannel();
                    //ChannelServices.RegisterChannel(chan, false);
                    IDictionary props = new Hashtable();
                    props["port"] = 0;
                    BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
                    serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
                    IChannel chan = new TcpChannel(props, null, serverProvider);
                    ChannelServices.RegisterChannel(chan, false);

                    //Metodo para poder usar el objeto remoto
                    RemotingConfiguration.RegisterActivatedClientType(typeof(IServCobro), dir);


                }

                IServCobro servidorCom = (IServCobro)Activator.GetObject(typeof(IServCobro), dir);

                return servidorCom.EnviarMensaje(msj);

            }
            catch (Exception)
            {
                return  new MensajeProtocolo(Protocolo.Header.RES, msj.Cmd, 0, Protocolo.OK + Protocolo.SEPARADOR + -1);
            }
        }

        
    }
}
